from logging.config import fileConfig
from sqlalchemy import engine_from_config
from sqlalchemy import pool
from alembic import context
import os
import sys

# 添加项目根目录到Python路径
sys.path.append(os.path.dirname(os.path.dirname(__file__)))

# 导入项目配置和模型
from app.core.config import settings
from app.models.base import Base
from app.models.user_config import UserConfig
from app.models.history import History

# 获取Alembic配置
config = context.config

# 如果有alembic.ini中配置的日志，则解释配置
if config.config_file_name is not None:
    fileConfig(config.config_file_name)

# 添加模型的元数据
target_metadata = Base.metadata

def get_url():
    """获取数据库URL"""
    return settings.DATABASE_URL

def run_migrations_offline() -> None:
    """
    以"离线"模式运行迁移
    """
    url = get_url()
    context.configure(
        url=url,
        target_metadata=target_metadata,
        literal_binds=True,
        dialect_opts={"paramstyle": "named"},
    )

    with context.begin_transaction():
        context.run_migrations()

def run_migrations_online() -> None:
    """
    以"在线"模式运行迁移
    """
    configuration = config.get_section(config.config_ini_section)
    configuration["sqlalchemy.url"] = get_url()
    connectable = engine_from_config(
        configuration,
        prefix="sqlalchemy.",
        poolclass=pool.NullPool,
    )

    with connectable.connect() as connection:
        context.configure(
            connection=connection,
            target_metadata=target_metadata,
            compare_type=True,
        )

        with context.begin_transaction():
            context.run_migrations()

if context.is_offline_mode():
    run_migrations_offline()
else:
    run_migrations_online() 